package com.pactera.asmp.server.pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.pactera.asmp.server.pojo.TaskStartupInfo;
import com.pactera.asmp.server.vo.DeviceTraceInfo;
import com.pactera.asmp.server.vo.ExcelDataVo;
import com.pactera.asmp.server.vo.ReportHmiStartRecord;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.pactera.asmp.server.common.constants.ApplicationResponseTimeEnum;
import com.pactera.asmp.server.entity.EmailReportDTO;
import com.pactera.asmp.server.entity.SelectTestReportResult;
import com.pactera.asmp.server.entity.TaskReportChartVO;
import com.pactera.asmp.server.entity.TestReportApplicationResponseTime;
import com.pactera.asmp.server.pojo.DeviceInfo;
import com.pactera.asmp.server.pojo.MasterComputer;
import com.pactera.asmp.server.pojo.TestReportErrorVideoInfo;

public class PdfProjectTestReport {

    private static final BaseColor COLOR_BLUE = new BaseColor(202, 215, 236);

    private static final BaseColor COLOR_GRAY = new BaseColor(229, 230, 234);

    // 最大宽度
    private static final int maxWidth = 470;
    private static Font headfont;
    private static Font keyfont;
    private static Font redKeyfont;
    private static Font keyfontWithUnderLine;
    private static Font redKeyfontWithUnderLine;
    private static BaseFont bfChinese = null;


    public static File generateTraceFile(Map<String, Object> dataMap, List<DeviceTraceInfo> traceList, boolean addWaterMask, String waterMask){
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            File file = File.createTempFile("pdfTmp", ".pdf");
            PdfWriter.getInstance(document, new FileOutputStream(file));

            // 3.打开文档
            document.open();

            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            headfont = new Font(bfChinese, 14, Font.NORMAL);
            keyfont = new Font(bfChinese, 10, Font.NORMAL);

            redKeyfont = new Font(bfChinese, 10, Font.NORMAL);
            redKeyfont.setColor(BaseColor.RED);
            keyfontWithUnderLine = new Font(bfChinese, 10, Font.UNDERLINE);
            redKeyfontWithUnderLine = new Font(bfChinese, 10, Font.UNDERLINE);
            redKeyfontWithUnderLine.setColor(BaseColor.RED);
            // 4.向文档中添加内容
            generateTracePDF(document, dataMap, traceList);

            // 5.关闭文档
            document.close();

            if(!addWaterMask) {
                return file;
            }
            // 待加水印的文件
            PdfReader reader = new PdfReader(new FileInputStream(file));

            File waterMaskfile = File.createTempFile("pdfTmpWaterMask", ".pdf");
            // 加完水印的文件
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(waterMaskfile));
            // 设置透明度
            PdfGState gs = new PdfGState();
            // pdf页数
            int pageCount = reader.getNumberOfPages() + 1;
            // 水印的高和宽
            int waterMarkHeight = 30;
            int watermarkWeight = 60;
            // 水印间隔距离
            int waterMarkInterval = 150;
            Rectangle pageRectangle;
            // 循环对每页插入水印
            for (int i = 1; i < pageCount; i++) {
                pageRectangle = reader.getPageSizeWithRotation(i);
                // 水印的起始
                PdfContentByte content = stamper.getOverContent(i);
                gs.setFillOpacity(0.5f);
                content.setGState(gs);
                // 开始
                content.beginText();
                // 设置颜色 默认为黑色
                content.setColorFill(BaseColor.LIGHT_GRAY);
                // 设置字体及字号
                content.setFontAndSize(bfChinese, 15);
                for (int height = waterMarkHeight; height < pageRectangle.getHeight(); height = height
                        + waterMarkInterval) {
                    for (int width = watermarkWeight; width < pageRectangle.getWidth() + watermarkWeight; width = width
                            + waterMarkInterval) {
                        // 添加水印文字并旋转30度角
                        content.showTextAligned(Element.ALIGN_LEFT, waterMask, width - watermarkWeight,
                                height - waterMarkHeight, 30);
                    }
                }
                content.endText();
            }
            stamper.close();
            reader.close();
            file.delete();
            return waterMaskfile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File generateFile(EmailReportDTO emailReportDTO, String buckUrl, boolean addWaterMask, String waterMask) throws FileNotFoundException, DocumentException {
        if(null == emailReportDTO) {
            return null;
        }
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            File file = File.createTempFile("pdfTmp", ".pdf");
            PdfWriter.getInstance(document, new FileOutputStream(file));

            // 3.打开文档
            document.open();

            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            headfont = new Font(bfChinese, 14, Font.NORMAL);
            keyfont = new Font(bfChinese, 10, Font.NORMAL);

            redKeyfont = new Font(bfChinese, 10, Font.NORMAL);
            redKeyfont.setColor(BaseColor.RED);
            keyfontWithUnderLine = new Font(bfChinese, 10, Font.UNDERLINE);
            redKeyfontWithUnderLine = new Font(bfChinese, 10, Font.UNDERLINE);
            redKeyfontWithUnderLine.setColor(BaseColor.RED);
            // 4.向文档中添加内容
            generatePDF(document, emailReportDTO, buckUrl);

            // 5.关闭文档
            document.close();

            if(!addWaterMask) {
                return file;
            }
            // 待加水印的文件
            PdfReader reader = new PdfReader(new FileInputStream(file));

            File waterMaskfile = File.createTempFile("pdfTmpWaterMask", ".pdf");
            // 加完水印的文件
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(waterMaskfile));
            // 设置透明度
            PdfGState gs = new PdfGState();
            // pdf页数
            int pageCount = reader.getNumberOfPages() + 1;
            // 水印的高和宽
            int waterMarkHeight = 30;
            int watermarkWeight = 60;
            // 水印间隔距离
            int waterMarkInterval = 150;
            Rectangle pageRectangle;
            // 循环对每页插入水印
            for (int i = 1; i < pageCount; i++) {
                pageRectangle = reader.getPageSizeWithRotation(i);
                // 水印的起始
                PdfContentByte content = stamper.getOverContent(i);
                gs.setFillOpacity(0.5f);
                content.setGState(gs);
                // 开始
                content.beginText();
                // 设置颜色 默认为黑色
                content.setColorFill(BaseColor.LIGHT_GRAY);
                // 设置字体及字号
                content.setFontAndSize(bfChinese, 15);
                for (int height = waterMarkHeight; height < pageRectangle.getHeight(); height = height
                        + waterMarkInterval) {
                    for (int width = watermarkWeight; width < pageRectangle.getWidth() + watermarkWeight; width = width
                            + waterMarkInterval) {
                        // 添加水印文字并旋转30度角
                        content.showTextAligned(Element.ALIGN_LEFT, waterMask, width - watermarkWeight,
                                height - waterMarkHeight, 30);
                    }
                }
                content.endText();
            }
            stamper.close();
            reader.close();
            file.delete();
            return waterMaskfile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static void generateTracePDF(Document document, Map<String, Object> dataMap, List<DeviceTraceInfo> traceList) throws DocumentException {

        String projectName = dataMap.get("projectName")==null?"":dataMap.get("projectName").toString();
        String startDate = dataMap.get("startDate")==null?"":dataMap.get("startDate").toString();
        String endDate = dataMap.get("endDate")==null?"":dataMap.get("endDate").toString();
        String currentTime = dataMap.get("currentTime")==null?"":dataMap.get("currentTime").toString();

        // 表格
        PdfPTable table = createTable(new float[] { 120, 75, 75, 100, 50, 50, 100 });
        // title
        table.addCell(createCell("测试报告", headfont, Element.ALIGN_CENTER, 1, 7, 5.0f, null));
        //
        table.addCell(createCell("基础数据", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));
        //1
        table.addCell(createCell("项目名称：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(projectName, keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("统计开始时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(startDate, keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
        //2
        table.addCell(createCell("创建时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(currentTime, keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("统计结束时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(endDate , keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
        //3
        table.addCell(createCell("任务类型： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell("定时执行", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("任务状态：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell("已完成", keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

//        table.addCell(createCell("任务状态： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
//        table.addCell(createCell(emailReportDTO.getTaskStatus(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
//        table.addCell(createCell("创建人：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
//        table.addCell(createCell(emailReportDTO.getUsername(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

        table.addCell(createCell("系统模块异常统计", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));
        if(CollectionUtils.isNotEmpty(traceList)){
            for(DeviceTraceInfo deviceTraceInfo : traceList) {
                PdfPCell cell1 = createCell("模块名称： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY);
                cell1.setBackgroundColor(COLOR_BLUE);
                table.addCell(cell1);
                table.addCell(createCell(deviceTraceInfo.getIssueProcessName(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                PdfPCell cell2 = createCell("设备VIN：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY);
                cell2.setBackgroundColor(COLOR_BLUE);
                table.addCell(cell2);
                table.addCell(createCell(deviceTraceInfo.getVinCode(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

                table.addCell(createCell("Crash次数： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(String.valueOf(deviceTraceInfo.getCrash()), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                table.addCell(createCell("最新Crash时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(deviceTraceInfo.getLastCrashTime(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

                table.addCell(createCell("ANR次数： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(String.valueOf(deviceTraceInfo.getAnr()), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                table.addCell(createCell("最新ANR时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(deviceTraceInfo.getLastAnrTime(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

                table.addCell(createCell("其他异常次数： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(String.valueOf(deviceTraceInfo.getOther()), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                table.addCell(createCell("最新其他异常时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(deviceTraceInfo.getLastOtherTime(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
            }
        }
        document.add(table);
    }

    private static void generatePDF(Document document, EmailReportDTO emailReportDTO, String buckUrl) throws DocumentException {
        // 表格
        PdfPTable table = createTable(new float[] { 120, 75, 75, 100, 50, 50, 100 });
        // title
        table.addCell(createCell("测试报告", headfont, Element.ALIGN_CENTER, 1, 7, 5.0f, null));

        table.addCell(createCell("基础数据", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));

        table.addCell(createCell("任务名称：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(emailReportDTO.getTaskName(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("创建时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(emailReportDTO.getCreateTime(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

        table.addCell(createCell("项目名称：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(emailReportDTO.getProjectName(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("执行开始时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(null == emailReportDTO.getExeStartTime() ? "":emailReportDTO.getExeStartTime(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

        table.addCell(createCell("任务类型： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(emailReportDTO.getTaskType(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("执行结束时间：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(null == emailReportDTO.getExeEndTime() ? "":emailReportDTO.getExeEndTime(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

        table.addCell(createCell("任务状态： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(emailReportDTO.getTaskStatus(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
        table.addCell(createCell("创建人：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
        table.addCell(createCell(emailReportDTO.getUsername(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

        table.addCell(createCell("设备数据", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));

        List<DeviceInfo> deviceInfos = emailReportDTO.getDeviceInfos();
        List<MasterComputer> masterComputers = emailReportDTO.getMasterComputers();
        if(CollectionUtils.isNotEmpty(deviceInfos) && CollectionUtils.isNotEmpty(masterComputers)) {

            Map<Integer, List<DeviceInfo>> deviceInfosMap = deviceInfos.stream().collect(Collectors.groupingBy(DeviceInfo::getMasterComputerId));
            for(int i = 0; i < masterComputers.size(); i++) {
                MasterComputer masterComputer = masterComputers.get(i);
                if(masterComputers.size() > 1) {
                    table.addCell(createCell("设备" + String.valueOf(i + 1), keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));

                }
                table.addCell(createCell("台架名称：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(masterComputer.getName(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                table.addCell(createCell("台架 MID：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(masterComputer.getCuid(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

                List<DeviceInfo> relatedDevices = deviceInfosMap.get(masterComputer.getId());
                Optional<DeviceInfo> mainOptional = relatedDevices.stream().filter(deviceInfo -> !deviceInfo.getAuxiliary()).findFirst();
                String mainDuid = "";
                if(mainOptional.isPresent()) {
                    mainDuid = mainOptional.get().getDuid();
                }
                table.addCell(createCell("主设备： ", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell(mainDuid, keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                List<DeviceInfo> auxiliaryDevices = relatedDevices.stream().filter(deviceInfo -> deviceInfo.getAuxiliary()).collect(Collectors.toList());
                for(int j = 0; j < auxiliaryDevices.size(); j++) {
                    table.addCell(createCell("辅助设备" + String.valueOf(j + 1) + "：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                    if(j%2 == 0) {
                        table.addCell(createCell(auxiliaryDevices.get(j).getDuid(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
                    }else {
                        table.addCell(createCell(auxiliaryDevices.get(j).getDuid(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                    }
                }
                if(auxiliaryDevices.size()%2 == 0) {
                    table.addCell(createCell("", keyfont, Element.ALIGN_LEFT, 1, 4, 5.0f, null));
                }

                if(mainOptional.isPresent() && StringUtils.isNotEmpty(mainOptional.get().getDisplayIdsStr())) {
                    String[] displayIds = JSONObject.parseObject(mainOptional.get().getDisplayIdsStr(), String[].class);
                    for(int j = 0; j < displayIds.length; j++) {
                        table.addCell(createCell("多屏设备" + String.valueOf(j + 1) + "：", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                        if(j%2 == 0) {
                            table.addCell(createCell(displayIds[j], keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                        }else {
                            table.addCell(createCell(displayIds[j], keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
                        }
                    }
                    if(displayIds.length%2 == 1) {
                        table.addCell(createCell("", keyfont, Element.ALIGN_LEFT, 1, 4, 5.0f, null));
                    }
                }
            }

        }

        if(emailReportDTO.getType() == 3) {
            if(emailReportDTO.getMonkeyTestReportResult() != null) {
                SelectTestReportResult monkeyTestReportResult = emailReportDTO.getMonkeyTestReportResult();
                table.addCell(createCell("脚本执行情况", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));
                table.addCell(createCell("包名", keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
                table.addCell(createCell("Crash", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                table.addCell(createCell("ANR", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));

                String packageNames = emailReportDTO.getPackages();
                if(StringUtils.isNotEmpty(packageNames)) {
                    Map<String, Map<String, String>> map = Maps.newHashMap();
                    if(StringUtils.isNotEmpty(monkeyTestReportResult.getMonkeyReport())) {
                        map.putAll(JSONObject.parseObject(
                                monkeyTestReportResult.getMonkeyReport(), new TypeReference<List<Map<String, String>>>(){}
                                ).stream().collect(Collectors.toMap(x -> x.get("packagesName"), v -> v, (v1, v2) -> v1)));
                    }
                    for(String packageName: packageNames.split(",")) {
                        table.addCell(createCell(packageName, keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
                        if(MapUtils.isNotEmpty(map) && map.containsKey(packageName)) {
                            table.addCell(createCell(map.get(packageName).get("crashCount"), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                            table.addCell(createCell(map.get(packageName).get("anrCount"), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                        }else {
                            table.addCell(createCell("0", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                            table.addCell(createCell("0", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                        }
                    }
                }

                table.addCell(createCell("脚本执行情况", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));
                table.addCell(createCell("执行包名", keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
                table.addCell(createCell("视频", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                table.addCell(createCell("日志", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));

                table.addCell(createCell(emailReportDTO.getPackages(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));

                Phrase phraseVideo = new Phrase();
                if(StringUtils.isNotEmpty(monkeyTestReportResult.getVideoFileIndex())) {
                    String[] strs = monkeyTestReportResult.getVideoFileIndex().split(",");
                    phraseVideo.add(new Paragraph("IVI：", keyfont));
                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                    linkIvI.setAnchor(buckUrl + strs[0]);
                    phraseVideo.add(linkIvI);
                    if(strs.length > 1) {
                        phraseVideo.add("\r\n");
                        phraseVideo.add(new Paragraph("辅助设备：", keyfont));
                        Chunk linkAux = new Chunk(buckUrl + strs[1], keyfontWithUnderLine);
                        linkAux.setAnchor(buckUrl + strs[1]);
                        phraseVideo.add(linkAux);
                    }
                }
                if(CollectionUtils.isNotEmpty(monkeyTestReportResult.getErrorVideoInfos())) {
                    for(TestReportErrorVideoInfo testReportErrorVideoInfo : monkeyTestReportResult.getErrorVideoInfos()) {
                        phraseVideo.add("\r\n");
                        switch (testReportErrorVideoInfo.getType()) {
                        case 1:
                            phraseVideo.add(new Paragraph("摄像头-花屏：", keyfont));
                            break;
                        case 2:
                            phraseVideo.add(new Paragraph("摄像头-黑屏：", keyfont));
                            break;
                        case 3:
                            phraseVideo.add(new Paragraph("摄像头-白屏：", keyfont));
                            break;
                        case 4:
                            phraseVideo.add(new Paragraph("摄像头-定屏：", keyfont));
                            break;
                        }
                        Chunk link1 = new Chunk(buckUrl + testReportErrorVideoInfo.getErrorVideoFileId(), keyfontWithUnderLine);
                        link1.setAnchor(buckUrl + testReportErrorVideoInfo.getErrorVideoFileId());
                        phraseVideo.add(link1);
                    }
                }
                table.addCell(createCell(phraseVideo, Element.ALIGN_CENTER, 1, 2, 5.0f, null));

                if(StringUtils.isNotEmpty(monkeyTestReportResult.getVideoFileIndex())) {
                    String[] strs = monkeyTestReportResult.getLogFileIndex().split(",");

                    Phrase phrase1 = new Phrase();
                    phrase1.add(new Paragraph("IVI：", keyfont));
                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                    linkIvI.setAnchor(buckUrl + strs[0]);
                    phrase1.add(linkIvI);
                    if(strs.length > 1) {
                        phrase1.add("\r\n");
                        phrase1.add(new Paragraph("辅助设备：", keyfont));
                        Chunk linkAux = new Chunk(buckUrl + strs[1], keyfontWithUnderLine);
                        linkAux.setAnchor(buckUrl + strs[1]);
                        phrase1.add(linkAux);
                    }
                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }else {
                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }
            }
        }else {
            table.addCell(createCell("脚本数据", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));

            table.addCell(createCell("脚本执行总数", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
            table.addCell(createCell("成功数", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, COLOR_GRAY));
            table.addCell(createCell("失败数", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
            table.addCell(createCell("未执行数", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, COLOR_GRAY));
            table.addCell(createCell("脚本执行次数", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));

            JSONObject jsonObject = new JSONObject();
            if(null != emailReportDTO.getReportByTask()) {
                jsonObject = JSONObject.parseObject(JSONObject.toJSONString(emailReportDTO.getReportByTask()));
            }
            if(null == jsonObject.get("chartExeCount")) {
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, null));
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, null));
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
            }else {
                List<TaskReportChartVO> taskReportExeCount = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("chartExeCount")), new TypeReference<List<TaskReportChartVO>>(){});
                Optional<TaskReportChartVO> totalCount = taskReportExeCount.stream().filter(t -> StringUtils.equals(t.getItem(), "totalCount")).findFirst();
                if(totalCount.isPresent()) {
                    table.addCell(createCell(toString(totalCount.get().getCount()), keyfont, Element.ALIGN_CENTER, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, null));
                }
                Optional<TaskReportChartVO> successCount = taskReportExeCount.stream().filter(t -> StringUtils.equals(t.getItem(), "successCount")).findFirst();
                if(successCount.isPresent()) {
                    emailReportDTO.setSuccessNum(successCount.get().getCount());
                    table.addCell(createCell(toString(successCount.get().getCount()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }
                Optional<TaskReportChartVO> failCount = taskReportExeCount.stream().filter(t -> StringUtils.equals(t.getItem(), "failCount")).findFirst();
                if(failCount.isPresent() && failCount.get().getCount() > 0) {
                    emailReportDTO.setFailNum(failCount.get().getCount());
                    table.addCell(createCell(toString(failCount.get().getCount()), redKeyfont, Element.ALIGN_CENTER, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, null));
                }
                Optional<TaskReportChartVO> waitCount = taskReportExeCount.stream().filter(t -> StringUtils.equals(t.getItem(), "waitCount")).findFirst();
                if(waitCount.isPresent()) {
                    emailReportDTO.setWaitNum(waitCount.get().getCount());
                    table.addCell(createCell(toString(waitCount.get().getCount()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }
            }
            table.addCell(createCell(toString(emailReportDTO.getExecNum()), keyfont, Element.ALIGN_CENTER, null));

            table.addCell(createCell("脚本类型：", keyfont, Element.ALIGN_CENTER, 2, 1, 5.0f, COLOR_GRAY));

            table.addCell(createCell("UI Case", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, COLOR_GRAY));
            table.addCell(createCell("Function Case", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, COLOR_GRAY));
            table.addCell(createCell("Others", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, COLOR_GRAY));

            if(null == jsonObject.get("chartCategory")) {
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
            }else {
                List<TaskReportChartVO> chartCategory = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("chartCategory")), new TypeReference<List<TaskReportChartVO>>(){});
                Optional<TaskReportChartVO> functionCase = chartCategory.stream().filter(t -> StringUtils.equals(t.getItem(), "UI case")).findFirst();
                if(functionCase.isPresent()) {
                    table.addCell(createCell(toString(functionCase.get().getCount()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }
                Optional<TaskReportChartVO> uiCase = chartCategory.stream().filter(t -> StringUtils.equals(t.getItem(), "Function case")).findFirst();
                if(uiCase.isPresent()) {
                    table.addCell(createCell(toString(uiCase.get().getCount()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }
                Optional<TaskReportChartVO> otherCase = chartCategory.stream().filter(t -> StringUtils.equals(t.getItem(), "Others")).findFirst();
                if(otherCase.isPresent()) {
                    table.addCell(createCell(toString(otherCase.get().getCount()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }else {
                    table.addCell(createCell("0", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                }
            }

            table.addCell(createCell("脚本执行情况", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));

            Map<Integer, List<SelectTestReportResult>> testReportResultMap= emailReportDTO.getTestReportResultMap();
            if(MapUtils.isNotEmpty(testReportResultMap)) {
                for(Integer key : testReportResultMap.keySet()) {
                    List<SelectTestReportResult> reportResultList = testReportResultMap.get(key);
                    Map<Boolean, List<SelectTestReportResult>> map = reportResultList.stream().collect(Collectors.groupingBy(x -> CollectionUtils.isEmpty(x.getTestedReport())));
                    Integer rowspan = 0;
                    for(Boolean bool: map.keySet()) {
                        if(bool) {
                            rowspan += map.get(bool).size() + 1;
                        }else {
                            for(SelectTestReportResult selectTestReportResult : map.get(bool)) {
                                rowspan += 2;
                                rowspan += selectTestReportResult.getTestedReport().size() * 4 + 1;
                            }
                        }
                    }
                    Phrase phrase = new Phrase();
                    phrase.add(new Paragraph(String.format("第【%d】次执行情况\r\n", key), keyfont));
                    Chunk titleLink = new Chunk("查看报告", keyfontWithUnderLine);
                    titleLink.setAnchor(emailReportDTO.getWebUrl());
                    phrase.add(titleLink);
                    table.addCell(createCell(phrase, Element.ALIGN_LEFT, rowspan, 1, 5.0f, null));

                    for (Boolean bool : map.keySet()) {
                        if (bool) {
                            table.addCell(createCell("脚本名称", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                            table.addCell(createCell("模块", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                            table.addCell(createCell("视频", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                            table.addCell(createCell("日志", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                            table.addCell(createCell("CAN", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                            table.addCell(createCell("HTMLReport", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                            for(SelectTestReportResult result : map.get(bool)) {
                                if(result.getStatus() != null && result.getStatus().intValue() == 1) {
                                    table.addCell(createCell(result.getScriptName(), keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(result.getModuleName(), keyfont, Element.ALIGN_CENTER, null));
                                }else {
                                    table.addCell(createCell(result.getScriptName(), redKeyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(result.getModuleName(), redKeyfont, Element.ALIGN_CENTER, null));
                                }
                                Phrase phraseVideo = new Phrase();
                                if(StringUtils.isNotEmpty(result.getVideoFileIndex())) {
                                    String[] strs = result.getVideoFileIndex().split(",");
                                    phraseVideo.add(new Paragraph("IVI：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phraseVideo.add(linkIvI);
                                    if(strs.length > 1) {
                                        phraseVideo.add("\r\n");
                                        phraseVideo.add(new Paragraph("辅助设备：", keyfont));
                                        Chunk linkAux = new Chunk(buckUrl + strs[1], keyfontWithUnderLine);
                                        linkAux.setAnchor(buckUrl + strs[1]);
                                        phraseVideo.add(linkAux);
                                    }
                                }
                                if(CollectionUtils.isNotEmpty(result.getErrorVideoInfos())) {
                                    for(TestReportErrorVideoInfo testReportErrorVideoInfo : result.getErrorVideoInfos()) {
                                        phraseVideo.add("\r\n");
                                        switch (testReportErrorVideoInfo.getType()) {
                                        case 1:
                                            phraseVideo.add(new Paragraph("摄像头-花屏：", keyfont));
                                            break;
                                        case 2:
                                            phraseVideo.add(new Paragraph("摄像头-黑屏：", keyfont));
                                            break;
                                        case 3:
                                            phraseVideo.add(new Paragraph("摄像头-白屏：", keyfont));
                                            break;
                                        case 4:
                                            phraseVideo.add(new Paragraph("摄像头-定屏：", keyfont));
                                            break;
                                        }
                                        Chunk link1 = new Chunk(buckUrl + testReportErrorVideoInfo.getErrorVideoFileId(), keyfontWithUnderLine);
                                        link1.setAnchor(buckUrl + testReportErrorVideoInfo.getErrorVideoFileId());
                                        phraseVideo.add(link1);
                                    }
                                }
                                table.addCell(createCell(phraseVideo, Element.ALIGN_CENTER, 1, 1, 5.0f, null));

                                if(StringUtils.isNotEmpty(result.getLogFileIndex())) {
                                    String[] strs = result.getLogFileIndex().split(",");

                                    Phrase phrase1 = new Phrase();
                                    phrase1.add(new Paragraph("IVI：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phrase1.add(linkIvI);
                                    if(strs.length > 1) {
                                        phrase1.add("\r\n");
                                        phrase1.add(new Paragraph("辅助设备：", keyfont));
                                        Chunk linkAux = new Chunk(buckUrl + strs[1], keyfontWithUnderLine);
                                        linkAux.setAnchor(buckUrl + strs[1]);
                                        phrase1.add(linkAux);
                                    }
                                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }else {
                                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }

                                if(StringUtils.isNotEmpty(result.getCanLogFileId())) {
                                    String[] strs = result.getCanLogFileId().split(",");

                                    Phrase phrase1 = new Phrase();
                                    phrase1.add(new Paragraph("CAN：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phrase1.add(linkIvI);
                                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }else {
                                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }

                                if(StringUtils.isNotEmpty(result.getHtmlReportFileId())) {
                                    String[] strs = result.getHtmlReportFileId().split(",");

                                    Phrase phrase1 = new Phrase();
                                    phrase1.add(new Paragraph("HTMLReport：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phrase1.add(linkIvI);

                                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }else {
                                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }
                            }
                        }else {
                            for(SelectTestReportResult result : map.get(bool)) {
                                table.addCell(createCell("脚本名称", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                                table.addCell(createCell("模块", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                                table.addCell(createCell("视频", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                                table.addCell(createCell("日志", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                                table.addCell(createCell("CAN", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                                table.addCell(createCell("HTMLReport", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, COLOR_GRAY));
                                if(result.getStatus() != null && result.getStatus().intValue() == 1) {
                                    table.addCell(createCell(result.getScriptName(), keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(result.getModuleName(), keyfont, Element.ALIGN_CENTER, null));
                                }else {
                                    table.addCell(createCell(result.getScriptName(), redKeyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(result.getModuleName(), redKeyfont, Element.ALIGN_CENTER, null));
                                }
                                Phrase phraseVideo = new Phrase();
                                if(StringUtils.isNotEmpty(result.getVideoFileIndex())) {
                                    String[] strs = result.getVideoFileIndex().split(",");
                                    phraseVideo.add(new Paragraph("IVI：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phraseVideo.add(linkIvI);
                                    if(strs.length > 1) {
                                        phraseVideo.add("\r\n");
                                        phraseVideo.add(new Paragraph("辅助设备：", keyfont));
                                        Chunk linkAux = new Chunk(buckUrl + strs[1], keyfontWithUnderLine);
                                        linkAux.setAnchor(buckUrl + strs[1]);
                                        phraseVideo.add(linkAux);
                                    }
                                }
                                if(CollectionUtils.isNotEmpty(result.getErrorVideoInfos())) {
                                    for(TestReportErrorVideoInfo testReportErrorVideoInfo : result.getErrorVideoInfos()) {
                                        phraseVideo.add("\r\n");
                                        switch (testReportErrorVideoInfo.getType()) {
                                        case 1:
                                            phraseVideo.add(new Paragraph("摄像头-花屏：", keyfont));
                                            break;
                                        case 2:
                                            phraseVideo.add(new Paragraph("摄像头-黑屏：", keyfont));
                                            break;
                                        case 3:
                                            phraseVideo.add(new Paragraph("摄像头-白屏：", keyfont));
                                            break;
                                        case 4:
                                            phraseVideo.add(new Paragraph("摄像头-定屏：", keyfont));
                                            break;
                                        }
                                        Chunk link1 = new Chunk(buckUrl + testReportErrorVideoInfo.getErrorVideoFileId(), keyfontWithUnderLine);
                                        link1.setAnchor(buckUrl + testReportErrorVideoInfo.getErrorVideoFileId());
                                        phraseVideo.add(link1);
                                    }
                                }
                                table.addCell(createCell(phraseVideo, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
    
                                if(StringUtils.isNotEmpty(result.getLogFileIndex())) {
                                    String[] strs = result.getLogFileIndex().split(",");
    
                                    Phrase phrase1 = new Phrase();
                                    phrase1.add(new Paragraph("IVI：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phrase1.add(linkIvI);
                                    if(strs.length > 1) {
                                        phrase1.add("\r\n");
                                        phrase1.add(new Paragraph("辅助设备：", keyfont));
                                        Chunk linkAux = new Chunk(buckUrl + strs[1], keyfontWithUnderLine);
                                        linkAux.setAnchor(buckUrl + strs[1]);
                                        phrase1.add(linkAux);
                                    }
                                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }else {
                                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }

                                if(StringUtils.isNotEmpty(result.getCanLogFileId())) {
                                    String[] strs = result.getCanLogFileId().split(",");

                                    Phrase phrase1 = new Phrase();
                                    phrase1.add(new Paragraph("CAN：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phrase1.add(linkIvI);
                                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }else {
                                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }

                                if(StringUtils.isNotEmpty(result.getHtmlReportFileId())) {
                                    String[] strs = result.getHtmlReportFileId().split(",");

                                    Phrase phrase1 = new Phrase();
                                    phrase1.add(new Paragraph("HTMLReport：", keyfont));
                                    Chunk linkIvI = new Chunk(buckUrl + strs[0], keyfontWithUnderLine);
                                    linkIvI.setAnchor(buckUrl + strs[0]);
                                    phrase1.add(linkIvI);

                                    table.addCell(createCell(phrase1, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }else {
                                    table.addCell(createCell("", keyfont, Element.ALIGN_CENTER, 1, 1, 5.0f, null));
                                }

                                table.addCell(createCell("监测类型", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                                table.addCell(createCell("属性", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                                table.addCell(createCell("平均时长", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));
                                table.addCell(createCell("最大时间", keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, COLOR_GRAY));
                                table.addCell(createCell("最小时间", keyfont, Element.ALIGN_CENTER, COLOR_GRAY));

                                for(TestReportApplicationResponseTime value: result.getTestedReport()) {
                                    table.addCell(createCell(ApplicationResponseTimeEnum.getDescription(value.getType()), keyfont, Element.ALIGN_LEFT, 4, 1, 5.0f, null));
                                    table.addCell(createCell("启动指令", keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getStartupResponseTimeMean().toString()), keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getStartupResponseTimeMax().toString()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                                    table.addCell(createCell(String.format("%s ms", value.getStartupResponseTimeMin().toString()), keyfont, Element.ALIGN_CENTER, null));

                                    table.addCell(createCell("启动画面", keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getStartupChangeTimeMean().toString()), keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getStartupChangeTimeMax().toString()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                                    table.addCell(createCell(String.format("%s ms", value.getStartupChangeTimeMin().toString()), keyfont, Element.ALIGN_CENTER, null));

                                    table.addCell(createCell("退出指令", keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getCloseResponseTimeMean().toString()), keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getCloseResponseTimeMax().toString()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                                    table.addCell(createCell(String.format("%s ms", value.getCloseResponseTimeMin().toString()), keyfont, Element.ALIGN_CENTER, null));

                                    table.addCell(createCell("退出面面", keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getCloseChangeTimeMean().toString()), keyfont, Element.ALIGN_CENTER, null));
                                    table.addCell(createCell(String.format("%s ms", value.getCloseChangeTimeMax().toString()), keyfont, Element.ALIGN_CENTER, 1, 2, 5.0f, null));
                                    table.addCell(createCell(String.format("%s ms", value.getCloseChangeTimeMin().toString()), keyfont, Element.ALIGN_CENTER, null));
                                }
                            }
                        }
                    }
                    
                }
            }
        }
        //冷热启动
        HashMap<String, List<TaskStartupInfo>> startupMap = emailReportDTO.getStartupMap();
        if(MapUtils.isNotEmpty(startupMap)) {
            table.addCell(createCell("冷热启动", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));

//            table.addCell(createCell("平均时间", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
//            table.addCell(createCell("最大时间", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
//            table.addCell(createCell("最小时间", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
//            table.addCell(createCell("执行次数", keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
            for(Map.Entry<String, List<TaskStartupInfo>> entry : startupMap.entrySet()){
                List<TaskStartupInfo> spList =  entry.getValue();
                if(CollectionUtils.isEmpty(spList)) {
                    continue;
                }
                table.addCell(createCell(entry.getKey(), keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));
                table.addCell(createCell("类型", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell("平均时间", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell("最大时间", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, COLOR_GRAY));
                table.addCell(createCell("最小时间", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell("执行次数", keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, COLOR_GRAY));
                for(TaskStartupInfo taskStartupInfo : spList){
                    String startupType = taskStartupInfo.getType()==1?"冷启动":"热启动";
                    table.addCell(createCell(startupType, keyfont, Element.ALIGN_LEFT, null));
                    table.addCell(createCell(taskStartupInfo.getStartupAvg(), keyfont, Element.ALIGN_LEFT, null));
                    table.addCell(createCell(taskStartupInfo.getStartupMax(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, null));
                    table.addCell(createCell(taskStartupInfo.getStartupMin(), keyfont, Element.ALIGN_LEFT, null));
                    table.addCell(createCell(taskStartupInfo.getCountNum().toString(), keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, null));
                }
            }
            ExcelDataVo.StatisticSheetData<ReportHmiStartRecord> sheetData = emailReportDTO.getSheetData();
            if(CollectionUtils.isNotEmpty(sheetData.getReportRecords())){
                table.addCell(createCell("冷热启动汇总", keyfont, Element.ALIGN_CENTER, 1, 7, 5.0f, COLOR_BLUE));
                table.addCell(createCell("packageName", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell("Cold Start", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, COLOR_GRAY));
                table.addCell(createCell("Warm Start", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                table.addCell(createCell("Hot Start", keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, COLOR_GRAY));
//                table.addCell(createCell("最小时间", keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
//                table.addCell(createCell("执行次数", keyfont, Element.ALIGN_LEFT, 1, 3, 5.0f, COLOR_GRAY));
                for(ReportHmiStartRecord record:sheetData.getReportRecords()){
                    table.addCell(createCell(record.getPackageName(), keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                    table.addCell(createCell(record.getColdStart(),  keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, COLOR_GRAY));
                    table.addCell(createCell(record.getWarmStart(), keyfont, Element.ALIGN_LEFT, COLOR_GRAY));
                    table.addCell(createCell(record.getHotStart(), keyfont, Element.ALIGN_LEFT, 1, 2, 5.0f, COLOR_GRAY));
                }
            }
        }
        //
        document.add(table);
    }

    /**
     * 创建指定列宽、列数的表格
     * 
     * @param widths
     * @return
     */
    private static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建单元格（指定字体、水平..）
     * 
     * @param value
     * @param font
     * @param align
     * @return
     */
    private static PdfPCell createCell(String value, Font font, int align, BaseColor baseColor) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPadding(5.0f);
        cell.setPhrase(new Phrase(value, font));
        cell.setBackgroundColor(baseColor == null ? BaseColor.WHITE : baseColor);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并）
     * 
     * @param value
     * @param font
     * @param align
     * @param rowspan
     * @param colspan
     * @param padding
     * @param baseColor
     * @return
     */
    private static PdfPCell createCell(String value, Font font, int align, int rowspan, int colspan, float padding, BaseColor baseColor) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setRowspan(rowspan);
        cell.setColspan(colspan);
        cell.setPadding(padding);
        cell.setPhrase(new Phrase(value, font));
        cell.setBackgroundColor(baseColor == null ? BaseColor.WHITE : baseColor);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并，超链接）
     * 
     * @param phrase
     * @param align
     * @param rowspan
     * @param colspan
     * @param padding
     * @param baseColor
     * @return
     */
    private static PdfPCell createCell(Phrase phrase, int align, int rowspan, int colspan, float padding, BaseColor baseColor) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setRowspan(rowspan);
        cell.setColspan(colspan);
        cell.setPadding(padding);
        cell.setPhrase(phrase);
        cell.setBackgroundColor(baseColor == null ? BaseColor.WHITE : baseColor);
        return cell;
    }

    private static String toString(Object obj) {
        if(obj == null) {
            return "";
        }
        return obj.toString();
    }
}
